﻿using Com.JunCaiSoft.AutoMapper;
using Com.JunCaiSoft.Common.Controller;
using Com.JunCaiSoft.Common.ExchangeData;
using Com.JunCaiSoft.Common.Model;
using Com.JunCaiSoft.Freeze.Dto;
using Com.JunCaiSoft.Freeze.Entity;
using Com.JunCaiSoft.Freeze.IDao;
using Com.JunCaiSoft.Freeze.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Com.JunCaiSoft.API.Freeze.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UnFreezeMoneyController : BaseController<UnFreezeMoneyView, UnFreezeMoneyItem, UnFreezeMoney, Guid>
    {
        public UnFreezeMoneyController(IUnFreezeMoneyDao unFreezeMoneyDao) : base(unFreezeMoneyDao)
        {

        }
        /// <summary>
        /// 按借条ID单个删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete]
        public override async Task<ActionResult> DeleteSingleAsync(Guid Id)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();
                int result = await DaoAsync.DeleteListAsync<UnFreezeMoney>(x => x.Id == Id);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 按借条ID批量删除
        /// </summary>
        /// <param name="DeleteList"></param>
        /// <returns></returns>
        [HttpPatch]
        public virtual async Task<ActionResult> DeleteList(IEnumerable<Guid> DeleteList)
        {
            try
            {
                await DaoAsync.dbContext.Database.BeginTransactionAsync();

                int result = await DaoAsync.DeleteListAsync<UnFreezeMoney>(x => DeleteList.Contains(x.Id));

                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                DaoAsync.dbContext.Database.CommitTransaction();
            }
        }
        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize"></param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ListByPageAsync(int pageIndex, int pageSize, String keyword)
        {
            try
            {
                var columns = @" um.Id,
	                             um.Num,
	                             um.NumCode,
	                             pt.NickName BranchCompany,
	                             pt.Boss BranchBoss,
	                             cc.Creditor ProjectManager,
	                             cc.CreditorID ProjectManagerID,
                                 cc.Rate,
                                 cc.RatePeriod,
	                             pj.Name FreezeProject,
	                             b.Name FreezeBank,
                                 b.Account BankAccount,
	                             p.CaseCode,
	                             cs.Name CaseStatus,
	                             fm.FactFreeze,
	                             fm.Amount FreezeMoney,
	                             um.Amount UnFreezeMoney,
	                             um.FreezeBalance,
	                             ft.Name FundsType,
	                             fm.FreezeTime,
	                             um.UnFreezeTime,
	                             fm.FreezeLoanConfirm,
	                             um.Remark,
	                             u.RealName,
	                             um.CreateTime ";

                var tables = @" UnFreezeMoney um
	                            LEFT JOIN FreezeMoney fm ON fm.Id = um.FreezeInfo
	                            LEFT JOIN FundsType ft ON fm.FundsType = ft.Code
	                            LEFT JOIN CreditContract cc ON fm.CreditContractInfo = cc.Id
	                            LEFT JOIN Bank b ON fm.FreezeBank = b.Id
	                            LEFT JOIN Preservation p ON fm.PreservationInfo = p.Id
	                            LEFT JOIN CaseMain cm ON cm.Id = p.CaseMainInfo
	                            LEFT JOIN CaseStatus cs ON cm.CaseStatus = cs.Code
	                            LEFT JOIN Project pj ON cm.CaseProject = pj.Id
	                            LEFT JOIN Partment pt ON pj.Partment = pt.Id
	                            LEFT JOIN [User] u ON um.UnFreezeOperator = u.Id ";

                var where = @" 1 = 1 ";

                List<SqlParameter> bankParams = new List<SqlParameter>() { };

                if (keyword != "" && keyword != null)
                {

                    Regex rex = new Regex(@"^\d{4}$");

                    if (keyword.Length == 4 && rex.IsMatch(keyword))
                    {
                        where += " AND cc.CreditorID like @BankNameOrBankTail ";

                        SqlParameter QueryBankName = new SqlParameter("@BankNameOrBankTail", "%" + keyword);

                        bankParams.Add(QueryBankName);
                    }
                    else
                    {
                        where += " AND pj.Name like @BankNameOrBankTail OR cc.Creditor OR b.Name like @BankNameOrBankTail ";

                        SqlParameter QueryBankName = new SqlParameter("@BankNameOrBankTail", "%" + keyword + "%");

                        bankParams.Add(QueryBankName);
                    }

                }

                var tmpResultList = await DaoAsync.QuerySQLByPageQuickAsync<UnFreezeMoneyItemDto>(pageIndex, pageSize, " um.CreateTime desc ", columns, tables, where, bankParams.Select(x => ((ICloneable)x).Clone()).ToArray());

                var resultList = new QueryData<UnFreezeMoneyItem>();

                var itemList = new List<UnFreezeMoneyItem>();

                resultList.totalCount = tmpResultList.totalCount;

                tmpResultList.items.ToList().ForEach(item => itemList.Add(item.MapTo<UnFreezeMoneyItem>()));

                resultList.items = itemList;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(resultList)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 创建借条信息
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public override async Task<ActionResult> CreateAsync(UnFreezeMoneyView entity)
        {
            try
            {
                DaoAsync.dbContext.Database.BeginTransaction();

                var saveone = entity.MapTo<UnFreezeMoney>();
                var result = await DaoAsync.InsertAsync(saveone);

                DaoAsync.dbContext.Database.CommitTransaction();
                return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
            }
            catch (Exception e)
            {
                throw e;
            }

        }
        /// <summary>
        /// 更新借条信息
        /// </summary>
        /// <param name="entityModel"></param>
        /// <returns></returns>
        [HttpPut]
        public override async Task<ActionResult> UpdateAsync(UpdateEntity<UnFreezeMoneyView> entityModel)
        {
            DaoAsync.dbContext.Database.BeginTransaction();

            var saveone = entityModel.entity.MapTo<UnFreezeMoney>();
            var result = await DaoAsync.UpdateAsync(saveone, entityModel.Id);

            DaoAsync.dbContext.Database.CommitTransaction();
            return await Task.Run(() => Content(JsonConvert.SerializeObject(result)));
        }
        /// <summary>
        /// 计算利息
        /// </summary>
        /// <param name="FreezeTime"></param>
        /// <param name="UnFreezeTime"></param>
        /// <param name="Amount"></param>
        /// <param name="FreezeRate"></param>
        /// <param name="FreezeRateType"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ComputeInterest(DateTime FreezeTime, DateTime UnFreezeTime, Double Amount, Double FreezeRate, String FreezeRateType)
        {
            try
            {
                var iDays = ((UnFreezeTime.ToString("yyyy-MM") == DateTime.MaxValue.ToString("yyyy-MM") ? DateTime.Now : UnFreezeTime) - FreezeTime).Days;

                Double interest = 0.0;

                switch (FreezeRateType)
                {
                    case "DAY":
                        interest = Amount * (FreezeRate / 100) * iDays;
                        break;
                    case "MONTH":
                        interest = Amount * (FreezeRate / 100 / 30) * iDays;
                        break;
                    case "YEAR":
                        interest = Amount * (FreezeRate / 100 / 360) * iDays;
                        break;
                    default:
                        interest = Amount * (FreezeRate / 100) * iDays;
                        break;
                }

                interest = Math.Round(interest, 2);

                return await Task.Run(() => Content(JsonConvert.SerializeObject(interest)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        /// <summary>
        /// 计算冻结日期
        /// </summary>
        /// <param name="FreezeTime"></param>
        /// <param name="UnFreezeTime"></param>
        /// <returns></returns>
        [HttpGet]
        public virtual async Task<ActionResult> ComputeFreezeDayCount(DateTime FreezeTime, DateTime UnFreezeTime)
        {
            try
            {
                var iDays = ((UnFreezeTime.ToString("yyyy-MM") == DateTime.MaxValue.ToString("yyyy-MM") ? DateTime.Now : UnFreezeTime) - FreezeTime).Days;

                return await Task.Run(() => Content(JsonConvert.SerializeObject(iDays)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}
